/* Copyright (c) 2010 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.orkut.client.api.samples.greetings.server.servlets;

import com.google.appengine.api.urlfetch.HTTPHeader;
import com.google.appengine.api.urlfetch.HTTPResponse;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.google.orkut.client.api.samples.greetings.server.AuthorizedChannel;
import com.google.orkut.client.api.samples.greetings.server.AuthorizedChannel.Factory;
import com.google.orkut.client.api.samples.greetings.shared.AuthorizationException;
import com.google.orkut.client.api.samples.greetings.shared.CommonConstants;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.BufferedOutputStream;
import java.io.IOException;

/**
 * Serves captcha by tunneling a 3-legged-oauth request to orkut.
 *
 * @author Shishir Birmiwal
 */
@Singleton
public class CaptchaServlet extends HttpServlet {

  public static final String CAPTCHA_IMG_PARAM = "captcha";
  private final Factory factory;

  @Inject
  public CaptchaServlet(AuthorizedChannel.Factory factory) {
    this.factory = factory;
  }

  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
      IOException {
    String st = req.getParameter(CommonConstants.SESSION_TOKEN_PARAM);
    String captchaImage = req.getParameter(CAPTCHA_IMG_PARAM);

    if (isEmpty(st) || isEmpty(captchaImage)) {
      resp.sendError(404, "invalid arguments");
      return;
    }

    AuthorizedChannel channel;
    try {
      channel = factory.create(st, req);
    } catch (AuthorizationException e) {
      throw new ServletException(e);
    }
    HTTPResponse response = channel.fetchUrl("http://www.orkut.com" + captchaImage);
    resp.setStatus(response.getResponseCode());
    for (HTTPHeader header : response.getHeaders()) {
      resp.addHeader(header.getName(), header.getValue());
    }
    BufferedOutputStream stream = new BufferedOutputStream(resp.getOutputStream());
    byte[] content = response.getContent();
    stream.write(content);
    stream.flush();
    stream.close();
  }

  boolean isEmpty(String str) {
    return str == null || str.trim().length() == 0;
  }
}
